package com.example.makerspace.manager;

import com.example.makerspace.dao.BookChapterDAO;
import com.example.makerspace.domain.BookChapterDO;
import com.example.makerspace.dto.BookChapterDTO;
import com.example.makerspace.dto.Result;
import com.example.makerspace.enums.ResultCodeEnum;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
public class BookChapterManager extends BaseManager<BookChapterDO, BookChapterDTO>{

    @Resource
    private BookChapterDAO bookChapterDAO;
    @Resource
    private BookManager bookManager;

    @PostConstruct
    public void init(){
        this.baseDAO = bookChapterDAO;
    }

    public Result addBookChapter(BookChapterDTO bookChapterDTO) {
        if(bookManager.selectByID(bookChapterDTO.getBookId()) == null){
            return Result.error(ResultCodeEnum.BOOK_NOT_EXIST);
        }
        BookChapterDO oldBookChapterDO = bookChapterDAO.selectDuplicate(bookChapterDTO);
        if(oldBookChapterDO != null){
            return Result.error(ResultCodeEnum.BOOK_CHAPTER_EXIST);
        }
        return addDO(bookChapterDTO);
    }

    public Result updateBookChapter(BookChapterDTO bookChapterDTO) {
        BookChapterDO bookChapterDO = bookChapterDAO.selectById(bookChapterDTO.getId());
        if(bookChapterDO == null){
            return Result.error(ResultCodeEnum.BOOK_CHAPTER_NOT_EXIST);
        }
        Optional.ofNullable(bookChapterDTO.getChapterName()).ifPresent(bookChapterDO::setChapterName);
        Optional.ofNullable(bookChapterDTO.getChapterContent()).ifPresent(bookChapterDO::setChapterContent);
        Optional.ofNullable(bookChapterDTO.getRichText()).ifPresent(bookChapterDO::setRichText);
        return updateDO(bookChapterDO);
    }



    public Result detail(BookChapterDTO bookChapterDTO) {
        Integer bookId = bookChapterDTO.getBookId();
        List<BookChapterDO> bookChapterDOS = bookChapterDAO.selectByBookId(bookId);
        List<BookChapterDTO> bookChapterDTOS = Optional.ofNullable(bookChapterDOS).orElse(Collections.emptyList())
                .stream().map(super::convert2DTO).collect(Collectors.toList());
        return Result.success(bookChapterDTOS);
    }
}
